package edu.tamu.cse.lenss.sensor;

import java.util.List;

import edu.tamu.cse.lenss.utils.Logger;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

public class AccController {
	private static final String TAG = AccController.class.getSimpleName();
	
	public static final int ACC_SENSITIVITY0 = SensorManager.SENSOR_DELAY_UI;
	public static final int ACC_SENSITIVITY1 = SensorManager.SENSOR_DELAY_NORMAL;
	public static final int ACC_SENSITIVITY2 = SensorManager.SENSOR_DELAY_GAME;
	public static final int ACC_SENSITIVITY3 = SensorManager.SENSOR_DELAY_FASTEST;
	
	private static int ACC_SAMPLING_RATE;
	private static boolean accOn = false;
	private final Context context;
	private final AccListener listener;
	
	private SensorManager myManager;
	private List<Sensor> sensors;
	private Sensor accSensor;
	
	public AccController(Context cont, AccListener lis){
		context = cont;
		listener = lis;
	}
	
	/**
	 * Return true if the accelerometer is available
	 */
	public boolean init(){
		myManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
		sensors = myManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
		if (sensors.size() > 0) {
			accSensor = sensors.get(0);
			return true;
		}
		else{
			Logger.e(TAG, "No Accelerometer is found");
			return false;
		}
	}	
	
	public void registerAcc(int sensitivity){
		ACC_SAMPLING_RATE = sensitivity;
		accOn=myManager.registerListener(mySensorListener, accSensor, ACC_SAMPLING_RATE);
	}
	
	public void unregisterAcc(){			
		accOn=false;
		myManager.unregisterListener(mySensorListener);			
	}
	
	public void resetFrequency(int newSensitivity){
		unregisterAcc();
		registerAcc(newSensitivity);
	}
	
	public boolean isAccOn(){
		return accOn;
	}
	
	private final SensorEventListener mySensorListener = new SensorEventListener() {
		private int sensorType;	
		public void onSensorChanged(SensorEvent event) {
			sensorType = event.sensor.getType();
			switch (sensorType){
			case Sensor.TYPE_ACCELEROMETER:
				listener.onNewValues(event.values.clone());
				break;
			}
		}
		
		public void onAccuracyChanged(Sensor sensor, int accuracy) {
		}
	};
	
	public static interface AccListener{
		void onNewValues(float[] values);
	}
}
